package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Yasd;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.view.SkillBookPop;

import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class YanShouSiCiActivity extends BaseActivity implements View.OnClickListener {
    private Yasd bean = new Yasd();
    private BaseRVAdapter adapter;
    private RecyclerView img;
    private List<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yan_shou_si_ci);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        //     bean = (Yasd) getIntent().getSerializableExtra("bean");
//        if (bean == null) {
//            MyToast("没有数据");
//            return;
//        }
//
//
//        title.setText("" + bean.getInfo().getName());
//        TextView name = (TextView) findViewById(R.id.name);
//        name.setText("" + bean.getInfo().getBudget_no());
//        TextView hetong = (TextView) findViewById(R.id.hetong);
//        hetong.setText("合同编号：" + bean.getInfo().getContract_id());
//        ImageView img2 = (ImageView) findViewById(R.id.img);
//        x.image().bind(img2, bean.getInfo().getImg());
//        TextView sname = (TextView) findViewById(R.id.sname);
//        sname.setText("" + bean.getInfo().getName());
//        TextView install = (TextView) findViewById(R.id.install);
//        install.setText("安装队：" + bean.getInfo().getInstall());
//        TextView ss = (TextView) findViewById(R.id.ss);
//        ss.setText("" + bean.getInfo().getLabel());
//        TextView info = (TextView) findViewById(R.id.info);
//        info.setText("" + bean.getInfo().getInfo());
//        RecyclerView max_re = (RecyclerView) findViewById(R.id.max_re);
//        max_re.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//        final List<Yasd.InfoEntity.ProgressEntity> progress = bean.getInfo().getProgress();
//        max_re.setAdapter(new BaseRVAdapter(this, progress) {
//            @Override
//            public int getLayoutId(int viewType) {
//                return R.layout.item_yanshou999;
//            }
//
//            @Override
//            public void onBind(BaseViewHolder holder, int position) {
//                holder.setTextView(R.id.fen, progress.get(position).getScore() + "分");
//                holder.setTextView(R.id.gai, progress.get(position).getRemark());
//                SwitchView switchButton = holder.getView(R.id.switchButton);
//                switchButton.setFlag(false);
//                if ("1".equals(progress.get(position).getIs_punish())) {
//                    switchButton.setOpened(true);
//                    holder.getView(R.id.chufa).setVisibility(View.VISIBLE);
//                    holder.setTextView(R.id.status55, progress.get(position).getPunish_money());
//                    holder.setTextView(R.id.shuoming, progress.get(position).getPunish_remark());
//                } else {
//                    switchButton.setOpened(false);
//                    holder.getView(R.id.chufa).setVisibility(View.GONE);
//                }
//                holder.setTextView(R.id.time, progress.get(position).getCheck_time());
//
//                RecyclerView diyici = holder.getView(R.id.diyici);
//                diyici.setLayoutManager(new GridLayoutManager(YanShouSiCiActivity.this, 4, LinearLayoutManager.VERTICAL, false));
//                final List<String> check_img = progress.get(position).getCheck_img();
//                diyici.setAdapter(new BaseRVAdapter(YanShouSiCiActivity.this, check_img) {
//                    @Override
//                    public int getLayoutId(int viewType) {
//                        return R.layout.item_photo;
//                    }
//
//                    @Override
//                    public void onBind(BaseViewHolder holder, final int position) {
//                        holder.getImageView(R.id.img).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                Intent intent = new Intent(YanShouSiCiActivity.this, ShowImageDetail.class);
//                                intent.putStringArrayListExtra("paths", (ArrayList<String>) check_img);
//                                intent.putExtra("index", position);
//                                startActivity(intent);
//                            }
//                        });
//                        //x.image().bind(holder.getImageView(R.id.img), bean.getInfo().getCheck_img().get(position));
//                        ImageLoader.getInstance().displayImage(check_img.get(position), holder.getImageView(R.id.img));
//
//                    }
//
//                });
//
//
//            }
//
//
//        });
        list.add("add");
        img = (RecyclerView) findViewById(R.id.imgs);
        img.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));

        adapter = new BaseRVAdapter(this, list) {

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_photo;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                if ("add".equals(list.get(position))) {
                    holder.getView(R.id.cha).setVisibility(View.GONE);
                    holder.getImageView(R.id.img).setImageResource(R.drawable.mq_ic_add_img);
                    holder.getImageView(R.id.img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPopmenu(v);
                        }
                    });
                } else {
                    holder.getImageView(R.id.img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(YanShouSiCiActivity.this, ShowImageDetail.class);
                            intent.putStringArrayListExtra("paths", (ArrayList<String>) list);
                            intent.putExtra("index", position);
                            startActivity(intent);
                        }
                    });
                    holder.getView(R.id.cha).setVisibility(View.VISIBLE);
                    x.image().bind(holder.getImageView(R.id.img), list.get(position));
                    holder.getView(R.id.cha).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            list.remove(position);
                            if (list.size() != 0) {
                                if (!"add".equals(list.get(list.size() - 1))) {
                                    list.add("add");
                                }
                            }
                            notifyDataSetChanged();
                        }
                    });
                }
            }

        };
        img.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
        }
    }

    /**
     * ------头像点击
     */
    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code
    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", "qqq.jpg")));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    System.out.println("imagePath**====www==" + imagePath);
                    updateImage(imagePath, uri);
                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", "qqq.jpg");
                    Uri uri = Uri.fromFile(tempFile);
                    String imagePath = tempFile.getAbsolutePath();
                    File file = new File(imagePath);
                    if (!file.exists()) {
                        return;
                    }
                    updateImage(imagePath, uri);
                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            default:
                break;
        }

    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }
        //  x.image().bind(iv_edit_head, "file://" + imagePath, options);

        if (list.size() < 4) {
            list.add(list.size() - 1, imagePath);
            adapter.notifyDataSetChanged();
        } else {
            list.add(list.size() - 1, imagePath);
            list.remove(list.size() - 1);
            adapter.notifyDataSetChanged();
        }
        Log.e("img", list.size() + "");
    }

}
